package bma.common.netty.webserver.ai;

import bma.common.langutil.ai.stack.AIStack;
import bma.common.langutil.ai.vm.AIVM;
import bma.common.netty.webserver.RequestContext;
import bma.common.netty.webserver.RequestDispatcher;
import bma.common.netty.webserver.RequestProcessor;
import bma.common.netty.webserver.SessionManager;
import bma.common.netty.webserver.WebServerUtil;

public class RequestProcess4AI implements RequestProcessor {

	protected AIVM vm;
	protected RequestRouter4AI router;
	protected RequestProcessor processor;

	public AIVM getVm() {
		return vm;
	}

	public void setVm(AIVM vm) {
		this.vm = vm;
	}

	public AIVM sureVm() {
		return this.vm == null ? AIVM.main() : this.vm;
	}

	public RequestProcessor getProcessor() {
		return processor;
	}

	public void setProcessor(RequestProcessor processor) {
		this.processor = processor;
	}

	public RequestRouter4AI getRouter() {
		return router;
	}

	public void setRouter(RequestRouter4AI router) {
		this.router = router;
	}

	public void setSessionRouter(SessionManager sm) {
		this.router = new SessionRouter4AI(sm);
	}

	@Override
	public boolean process(final AIStack<Boolean> stack,
			final RequestContext ctx) throws Exception {
		Object ro = null;
		if (this.router != null) {
			ro = this.router.apply(ctx);
		}
		return sureVm().execute(ro, new Runnable() {

			@Override
			public void run() {
				try {
					if (!RequestDispatcher.dispatchOrProcess(stack, processor,
							ctx)) {
						WebServerUtil.endWithNotFound("Processor4AI", ctx);
						stack.success(true);
					}
				} catch (Exception e) {
					stack.failure(e);
				}
			}
		});
	}

}
